$NG.AllReady(function (page, { useUpdateRow, useValuesChange, useUpdateRows,useDataIndexChange }) {
    const mstform = $NG.getCmpApi("p_form_proj_audit");
    const grid1 = $NG.getCmpApi("p_form_proj_audit_inner");
    const grid2 = $NG.getCmpApi("p_form_proj_audit_outer");

       {//初始化逻辑BEGIN
        if (mstform) {
            console.log(mstform.name + ' is ready');
            cntMFilter();
        } else {
            console.error('mstform is not available');
        };
    }//初始化逻辑END

    if (page.oType == "add") {
        var pc = mstform.getItem("phid_pc");
        getCntCount("p_form_proj_audit","u_cnt_name",()=>{
            getCntMInfoByPhid()
        })
        console.log("123123");
        if (pc.getValue() > "0") {
            cntMFilter()
            getNsInfo_inner(pc.getValue())
            getNsInfo_outer(pc.getValue())

            $NG.execServer("GetAuditInfo", { pc: pc.getValue() }, function (res) {
                console.log(res);
                if (res.count == "1") {
                    const data = JSON.parse(res.data);
                    const u_cnt_no = data[0].extendObjects.u_cnt_no;
                    const bill_no = data[0].extendObjects.bill_no;
                    const cntid = data[0].extendObjects.cntid;
                    const cntname = data[0].extendObjects.cntname;

                    $NG.updateState((updater) => {
                        updater.data.p_form_proj_audit.setProps({
                            u_cnt_no: u_cnt_no,
                            u_cnt_name: {
                                value: cntid,
                                label: cntname,
                            },
                            u_jsd_no: bill_no,
                        });
                    });
                    console.log(cntid)
                    getNsInfo_inner(cntid)
                    getNsInfo_outer(cntid)

                }
            });

            

            var pcname = mstform.getItem("phid_pc").getRawValue().label
            $NG.updateState((updater) => {
                //文本
                updater.data.p_form_proj_audit.setProps({
                    bill_name: pcname + "工程审计",
                });
            });


        }
    }

    //项目名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {
        console.log(args[0]);
        //const phid_pc = args[0].pc.PhId;
        const phid_pc = args[0].phid_pc.value;
        //从项目取值
        if (phid_pc) {
            console.log(phid_pc);
            //从项目取值
            cntMFilter()

            getNsInfo_inner(phid_pc)
            getNsInfo_outer(phid_pc)
            // $NG.execServer("GetAuditInfo", { pc: phid_pc }, function (res) {
            //     if (res.count) return  
            //         const data = JSON.parse(res.data);
            //         const bill_no = data[0].extendObjects.bill_no;
            //         const cntid = data[0].extendObjects.cntid;
            //         const u_jsje = data[0].extendObjects.u_jsje;

            //         $NG.updateState((updater) => {
            //             updater.data.p_form_proj_audit.setProps({
            //                 u_jsd_no: bill_no,
            //                 u_jsje: u_jsje,

            //             });
            //         });
            // });

        }

        var pcname = mstform.getItem("phid_pc").getRawValue().label
        $NG.updateState((updater) => {
            //文本
            updater.data.p_form_proj_audit.setProps({
                bill_name: pcname + "工程审计",
            });
        });
        getCntCount("p_form_proj_audit","u_cnt_name",()=>{
            getCntMInfoByPhid()
        })
    }, "p_form_proj_audit.phid_pc");

    //合同名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {
        console.log(args[0]);
        //const phid_pc = args[0].pc.PhId;
        const u_cnt_name = args[0].u_cnt_name.value;
        //从项目取值
        if (u_cnt_name) {
            console.log(u_cnt_name);
            //从项目取值
            $NG.execServer("getAduitHtInfo", { ht: u_cnt_name }, function (res) {
                const data = JSON.parse(res.data);
                const u_cnt_no = data[0].extendObjects.u_cnt_no;
                const bill_no = data[0].extendObjects.bill_no;
                const cntid = data[0].extendObjects.cntid;
                const cntname = data[0].extendObjects.cntname;
                const u_jsje = data[0].extendObjects.u_jsje;
                
                $NG.updateState((updater) => {
                    updater.data.p_form_proj_audit.setProps({
                        u_jsd_no: bill_no,
                        u_jsje: u_jsje,
   
                    });
                });
                getNsInfo_inner(cntid)
                getNsInfo_outer(cntid)
                getCntMInfoByPhid()
            });
        }
    }, "p_form_proj_audit.u_cnt_name");


    useUpdateRows(({ args }) => {
        var sumAmt = 0;
        const rows = args[0];
        var outer = mstform.getItem("u_outer").getValue();

        rows.forEach((items) => {
            if (items.u_adjust_hsje) {
                sumAmt += parseFloat(items.u_adjust_hsje); //明细
            }
            //汇总赋值

            $NG.updateState((updater) => {
                updater.data.p_form_proj_audit.setProps({
                    u_inner: sumAmt, //表头：
                    u_jstzje: sumAmt + outer, //表头：
                });
            });
        });
    }, "p_form_proj_audit_inner");

    useUpdateRows(({ args }) => {
        var sumAmt = 0;
        const rows = args[0];
        var inner = mstform.getItem("u_inner").getValue();

        rows.forEach((items) => {
            if (items.u_adjust_hsje) {
                sumAmt += parseFloat(items.u_adjust_hsje); //明细
            }
            //汇总赋值
            $NG.updateState((updater) => {
                updater.data.p_form_proj_audit.setProps({
                    u_outer: sumAmt, //表头：
                    u_jstzje: sumAmt + inner, //表头：
                });
            });
        });
    }, "p_form_proj_audit_outer");

    // useUpdateRow(({ args, table }) => {
    //     const record = args[0];
    //     //预估总价
    //     if (record.u_jsgcl && record.u_adjust_prc) {
    //         record.u_adjust_jshs = (
    //             parseFloat(record.u_jsgcl) * parseFloat(record.u_adjust_prc))
    //     }
    //     if (record.u_jshsje && record.u_adjust_jshs) {
    //         record.u_adjust_hsje = (
    //             parseFloat(record.u_jshsje) - parseFloat(record.u_adjust_jshs))
    //     }
    //     tables.updateRow(record);
    // }, "p_form_proj_audit_inner");




    useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)
        const u_adjust_gcl = record.u_adjust_gcl;
        const u_adjust_prc = record.u_adjust_prc;
        const u_jshsje = record.u_jshsje;
        const taxrate = record.taxrate;

        record.u_adjust_jshs = u_adjust_gcl * u_adjust_prc
        record.u_adjust_hsje = u_jshsje - u_adjust_gcl * u_adjust_prc
        record.u_jsse = u_adjust_gcl * taxrate * u_adjust_prc
        
        grid1.updateRow(args[0]);
        grid2.updateRow(args[0]);
      }, "u_adjust_gcl");

      useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)
        const u_adjust_gcl = record.u_adjust_gcl;
        const u_adjust_prc = record.u_adjust_prc;
        const u_jshsje = record.u_jshsje;
        const taxrate = record.taxrate;

        record.u_adjust_jshs = u_adjust_gcl * u_adjust_prc
        record.u_adjust_hsje = u_jshsje - u_adjust_gcl * u_adjust_prc
        record.u_jsse = u_adjust_gcl * taxrate * u_adjust_prc
        grid1.updateRow(args[0]);
        grid2.updateRow(args[0]);

      }, "u_adjust_prc");

    // 获取合同信息
    page.oType !='view' && getCntMInfoByPhid()
    function getCntMInfoByPhid(params) {
      if(!mstform.getItem("u_cnt_name").getValue()) return
      $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        $NG.updateState((updater) => {
          updater.data.p_form_proj_audit.setProps({
            u_cnt_no: datas.pcm_no, //合同编号
          });
        });
      });
    }

    //获取合同数量
  function getCntCount(table, key, fun, otherFun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              fun();
              if (otherFun) {
                otherFun();
              }
            }, 200);
          });
      }
    });
  }

});
function getNsInfo_inner(pcvalue) {
    const grid1 = $NG.getCmpApi("p_form_proj_audit_inner");

    $NG.execServer('GetAduitInner', { pc: pcvalue }, function (res) {
        const data = JSON.parse(res.data);
        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        grid1.clearRows();
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_sbqd_no: '',
                u_sbqd_name: '',
                u_ggxh: '',
                u_jscs: '',
                u_unit: '',
                prc: '',
                u_adjust_prc: '',
                qty: '',
                u_sbqd_qty: '',
                u_jsgcl: '',
                u_adjust_gcl: '',
                u_jshsje: '',
                u_adjust_jshs: '',
                taxrate: '',
                u_jsse: '',
                u_adjust_hsje: '',

            };
            gridObj.u_sbqd_no = data[i].extendObjects.u_sbqd_no;
            gridObj.u_sbqd_name = data[i].extendObjects.u_sbqd_name;
            gridObj.u_sbqd_name_EXName = data[i].extendObjects.u_equipment_list_name
            gridObj.u_ggxh = data[i].extendObjects.u_ggxh;
            gridObj.u_jscs = data[i].extendObjects.u_jscs;
            gridObj.u_unit = data[i].extendObjects.u_unit;
            gridObj.u_unit_EXName = data[i].extendObjects.msname;
            gridObj.prc = data[i].extendObjects.prc;
            gridObj.u_adjust_prc = data[i].extendObjects.prc;
            gridObj.qty = data[i].extendObjects.qty;
            gridObj.u_sbqd_qty = data[i].extendObjects.u_sbqd_qty;
            gridObj.u_jsgcl = data[i].extendObjects.u_bsby;
            gridObj.u_adjust_gcl = data[i].extendObjects.u_bsby;
            gridObj.u_jshsje = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.u_adjust_jshs = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.taxrate = data[i].extendObjects.taxrate;
            gridObj.u_jsse = data[i].extendObjects.u_bsbyhs_amt-data[i].extendObjects.u_bsby_amt;
            gridObj.u_adjust_hsje = '0';

            gridArr.push(gridObj);
        }

        // 清空表格内容（放在循环外部）
        grid1.clearRows();

        // 调用新增表体行数据的函数
        grid1.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid1.refreshView(); // 或者使用grid.refreshData();
    });



}


function getNsInfo_outer(pcvalue) {
    const grid2 = $NG.getCmpApi("p_form_proj_audit_outer");

    $NG.execServer('GetAuditOuter', { pc: pcvalue }, function (res) {
        const data = JSON.parse(res.data);
        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        grid2.clearRows();
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_sbqd_no: '',
                u_sbqd_name: '',
                u_ggxh: '',
                u_jscs: '',
                u_unit: '',
                prc: '',
                u_adjust_prc: '',
                qty: '',
                u_sbqd_qty: '',
                u_jsgcl: '',
                u_adjust_gcl: '',
                u_jshsje: '',
                u_adjust_jshs: '',
                taxrate: '',
                u_jsse: '',
                u_adjust_hsje: '',
            };
            gridObj.u_sbqd_no = data[i].extendObjects.u_sbqd_no;
            gridObj.u_sbqd_name = data[i].extendObjects.u_sbqd_name;
            gridObj.u_sbqd_name_EXName = data[i].extendObjects.u_equipment_list_name
            gridObj.u_ggxh = data[i].extendObjects.u_ggxh;
            gridObj.u_jscs = data[i].extendObjects.u_jscs;
            gridObj.u_unit = data[i].extendObjects.u_unit;
            gridObj.u_unit_EXName = data[i].extendObjects.msname;
            gridObj.prc = data[i].extendObjects.prc;
            gridObj.u_adjust_prc = data[i].extendObjects.prc;
            gridObj.qty = data[i].extendObjects.qty;
            gridObj.u_sbqd_qty = data[i].extendObjects.u_sbqd_qty;
            gridObj.u_jsgcl = data[i].extendObjects.u_bsby;
            gridObj.u_adjust_gcl = data[i].extendObjects.u_bsby;
            gridObj.u_jshsje = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.u_adjust_jshs = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.taxrate = data[i].extendObjects.taxrate;
            gridObj.u_jsse = data[i].extendObjects.u_bsbyhs_amt-data[i].extendObjects.u_bsby_amt;
            gridObj.u_adjust_hsje = '0';

            gridArr.push(gridObj);
        }
        // 清空表格内容（放在循环外部）
        grid2.clearRows();

        // 调用新增表体行数据的函数
        grid2.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid2.refreshView(); // 或者使用grid.refreshData();
    });



}
    //合同根据项目ID过滤
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log('过滤参数检查', updater);
            updater.fieldSetForm.p_form_proj_audit.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue() && {
                    clientSqlFilter: {
                        'pcm3_cnt_m.phid_pc': $NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue()
                    }
                }),
            });
        });
    }